﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Up2Link.Client;
using Up2Link.SegString;
using Up2Link.Util;

namespace LastLandClient
{
    public class CLastLandClient
    {
        private static CClient<CMessageSS> client = null;
        private static Boolean clientOn = false;

        public static void Main(string[] _args)
        {                        
            CConsole console = new CConsole();

            clientOn = true;
            console.SendOutput("欢迎使用《废土 Last Land (开发名)》客户端程序");
            console.SendOutput("输入help阅读客户端使用说明");
            console.Start();
            while (clientOn)
            {
                String input = console.ReceiveInput();
                if (input != null)
                {
                    Char[] d = { ':' };
                    String[] split = input.Split(d);
                    if (split.Length >= 2)
                    {
                        Command(console, split[0].ToLowerInvariant().Trim(), split[1].ToLowerInvariant().Trim());
                    }
                    else
                    {
                        Command(console, split[0].ToLowerInvariant().Trim(), null);
                    }
                }
                if (client != null && client.isClientOn())
                {
                    CMessageSS msg = client.Receive();
                    if (msg != null)
                    {
                        Message(console, msg);
                    }
                }
                if (client != null && !client.isClientOn())
                {
                    client = null;
                    console.SendOutput("");
                    console.SendOutput("客户端遇到异常，请重新连接服务器");
                }
            }
            console.Close();
        }

        private static void Command(CConsole _console, String _command, String _args)
        {
            if (_command.Equals("exit"))
            {
                clientOn = false;
                CloseClient(_console);
            }
            else if (_command.Equals("help"))
            {
                Help(_console);
            }
            else if (_command.Equals("talk"))
            {
                Talk(_console, _args);
            }
            else if (_command.Equals("start"))
            {
                if (_args != null)
                {
                    Char[] d = { ' ' };
                    String[] args = _args.Split(d);
                    if (args.Length >= 2)
                    {
                        StartClient(_console, args[0].Trim(), Int32.Parse(args[1].Trim()));
                    }
                    else
                    {
                        StartClient(_console, args[0].Trim(), 8802);
                    }
                }
                else
                {
                    _console.SendOutput("");
                    _console.SendOutput("你输入的指令是：" + _command);
                    _console.SendOutput("指令参数过少");
                }
            }
            else if (_command.Equals("close"))
            {
                CloseClient(_console);
            }
            else if (_command.Equals("restart"))
            {
                if (_args != null)
                {
                    Char[] d = { ' ' };
                    String[] args = _args.Split(d);
                    if (args.Length >= 2)
                    {
                        RestartClient(_console, args[0].Trim(), Int32.Parse(args[1].Trim()));
                    }
                    else
                    {
                        RestartClient(_console, args[0].Trim(), 8802);
                    }
                }
                else
                {
                    _console.SendOutput("");
                    _console.SendOutput("你输入的指令是：" + _command);
                    _console.SendOutput("指令参数过少");
                }
            }
            else if (_command.Equals("newuser"))
            {
                if (_args != null)
                {
                    Char[] d = { ' ' };
                    String[] args = _args.Split(d);
                    if (args.Length == 2)
                    {
                        NewUser(_console, args[0].Trim(), args[1].Trim());
                    }
                    else
                    {
                        _console.SendOutput("");
                        _console.SendOutput("你输入的指令是：" + _command);
                        _console.SendOutput("指令应该接受2个参数");
                    }
                }
                else
                {
                    _console.SendOutput("");
                    _console.SendOutput("你输入的指令是：" + _command);
                    _console.SendOutput("指令参数过少");
                }
            }
            else if (_command.Equals("login"))
            {
                if (_args != null)
                {
                    Char[] d = { ' ' };
                    String[] args = _args.Split(d);
                    if (args.Length == 2)
                    {
                        Login(_console, args[0].Trim(), args[1].Trim());
                    }
                    else
                    {
                        _console.SendOutput("");
                        _console.SendOutput("你输入的指令是：" + _command);
                        _console.SendOutput("指令应该接受2个参数");
                    }
                }
                else
                {
                    _console.SendOutput("");
                    _console.SendOutput("你输入的指令是：" + _command);
                    _console.SendOutput("指令参数过少");
                }
            }
            else if (_command.Equals("logout"))
            {
                Logout(_console);
            }
            else
            {
                _console.SendOutput("");
                _console.SendOutput("你输入的指令是：" + _command);
                _console.SendOutput("无法解析的指令，输入help阅读服务器使用说明");
            }
        }

        private static void Logout(CConsole _console)
        {
            CMessageSS logoutMsg = new CMessageSS(13, 0, 0, "");
            client.Send(logoutMsg);

            _console.SendOutput("");
            _console.SendOutput("登出的请求已发送给服务器");
        }

        private static void Login(CConsole _console, String _username, String _password)
        {
            CMessageSS loginUsernameMsg = new CMessageSS(12, 1, 0, _username);
            CMessageSS loginPasswordMsg = new CMessageSS(12, 0, 0, CMD5Hash.GetMD5Hash(_password));
            client.Send(loginUsernameMsg);
            client.Send(loginPasswordMsg);

            _console.SendOutput("");
            _console.SendOutput("登录的请求已发送给服务器");
            _console.SendOutput("用户名：" + _username + " 密码（MD5）：" + CMD5Hash.GetMD5Hash(_password));
        }

        private static void NewUser(CConsole _console, String _username, String _password)
        {
            CMessageSS newUsernameMsg = new CMessageSS(11, 1, 0, _username);
            CMessageSS newPasswordMsg = new CMessageSS(11, 0, 0, CMD5Hash.GetMD5Hash(_password));
            client.Send(newUsernameMsg);
            client.Send(newPasswordMsg);

            _console.SendOutput("");
            _console.SendOutput("创建新用户的请求已发送给服务器");
            _console.SendOutput("用户名：" + _username + " 密码（MD5）：" + CMD5Hash.GetMD5Hash(_password));
        }

        private static void Iplist(CConsole _console)
        {
            _console.SendOutput("");
            CIPProbe ipProbe = new CIPProbe();
            Int32 addressCount = ipProbe.AddressCount;
            if (addressCount > 0)
            {
                _console.SendOutput("这台机器的ip地址列表：");
                for (Int32 i = 0; i < addressCount; i++)
                {
                    _console.SendOutput(i + " ： " + ipProbe.AdrStrings[i]);
                }
            }
            else
            {
                _console.SendOutput("无法找到这台机器的ip地址");
            }
        }

        private static void Help(CConsole _console)
        {
            _console.SendOutput("");
            FileStream fs = new FileStream("help.txt", FileMode.OpenOrCreate);
            StreamReader sr = new StreamReader(fs);

            String line = sr.ReadLine();
            Char[] d = { '@' };
            while (line != null)
            {
                String[] cmdDoc = line.Split(d);
                foreach (String str in cmdDoc)
                {
                    _console.SendOutput(str);
                }
                line = sr.ReadLine();
            }

            fs.Close();
        }

        private static void Talk(CConsole _console, String _args)
        {
            if (client != null && client.isClientOn())
            {
                CMessageSS talkMsg = new CMessageSS(1, 0, 0, _args);
                client.Send(talkMsg);
            }
        }

        private static void StartClient(CConsole _console, String _address, Int32 _port)
        {
            if (client == null)
            {
                client = new CClient<CMessageSS>();
                client.Start(_address, _port);

                _console.SendOutput("");
                _console.SendOutput("客户端启动，连接到 " + _address + ":" + _port);
            }
            else
            {
                _console.SendOutput("");
                _console.SendOutput("客户端已经启动");
            }
        }

        private static void CloseClient(CConsole _console)
        {
            if (client != null && client.isClientOn())
            {
                client.Close();
                client = null;

                _console.SendOutput("");
                _console.SendOutput("客户端关闭");
            }
            else
            {
                _console.SendOutput("");
                _console.SendOutput("客户端已经关闭");
            }
        }

        private static void RestartClient(CConsole _console, String _address, Int32 _port)
        {
            if (client != null && client.isClientOn())
            {
                client.Close();
                client = new CClient<CMessageSS>();
                client.Start(_address, _port);

                _console.SendOutput("");
                _console.SendOutput("客户端重新启动，连接到 " + _address + ":" + _port);
            }
            else
            {
                _console.SendOutput("");
                _console.SendOutput("客户端已经关闭");
            }
        }

        private static void Message(CConsole _console, CMessageSS _msg)
        {
            if (_msg.MsgCode == 0)
            {
                client.Close();
                client = null;

                _console.SendOutput("");
                _console.SendOutput("服务器关闭，客户端断开连接");
            }
            else if (_msg.MsgCode == 10)
            {
                _console.SendOutput("");
                _console.SendOutput("指令执行成功");
            }
            else if (_msg.MsgCode == 11)
            {
                _console.SendOutput("");
                _console.SendOutput("用户名已经被创建：" + _msg.MsgContent);
            }
            else if (_msg.MsgCode == 12)
            {
                _console.SendOutput("");
                _console.SendOutput("用户名尚未被创建：" + _msg.MsgContent);
            }
            else if (_msg.MsgCode == 13)
            {
                _console.SendOutput("");
                _console.SendOutput("用户已经登录游戏：" + _msg.MsgContent);
            }
            else if (_msg.MsgCode == 14)
            {
                _console.SendOutput("");
                _console.SendOutput("用户尚未登录游戏：" + _msg.MsgContent);
            }
            else if (_msg.MsgCode == 15)
            {
                _console.SendOutput("");
                _console.SendOutput("用户名存在非法字符：" + _msg.MsgContent);
            }
            else if (_msg.MsgCode == 16)
            {
                _console.SendOutput("");
                _console.SendOutput("密码不正确：" + _msg.MsgContent);
            }
            else
            {
                _console.SendOutput("");
                //_console.SendOutput(_msg.MsgCode.ToString());
                //_console.SendOutput(_msg.MsgContent);
                _console.SendOutput(_msg.ToString());
            }            
        }
    }
}
